<template>
  <div id="app" style="font-size: 26px; font-weght: bold; margin: 30px 0">
    <header class="header">
      <el-button type="primary" icon="el-icon-plus" @click="handleEdit"
        >添加</el-button
      >
    </header>
    <el-breadcrumb separator="/" class="beeadBox">
      <el-breadcrumb-item
        class="breadItem"
        v-for="(item, index) in topInputList"
        :key="index"
      >
        <span @click="backStor(index, item.id)">{{ item.title }}</span>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <el-table v-loading="loading" :data="tableData" max-height="600" border fit>
      <el-table-column show-overflow-tooltip prop="id" label="ID" width="80">
      </el-table-column>
      <el-table-column show-overflow-tooltip label="分类名称">
        <template slot-scope="scope">
          <div class="nametitle" @click="subdirectory(scope.$index, scope.row)">
            {{ scope.row.name }}
          </div>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="分类图标" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.aimages.length > 0"
            style="width: 30px; height: 30px"
            :src="scope.row.aimages[0]"
            :preview-src-list="scope.row.aimages"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="sort"
        label="排序"
        width="120"
      >
      </el-table-column>
      <el-table-column show-overflow-tooltip label="前台显示" width="110">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="2"
            @change="switchChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" @click="deleteBtn(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40, 50, 60]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="outerVisible"
      :before-close="handleClosediaLoding"
    >
      <el-form
        label-position="right"
        label-width="80px"
        :model="formLabelAlign"
        :rules="rules"
        ref="ruleForm"
      >
        <div class="oneLine">
          <el-form-item label="所属分类" prop="parent_id">
            <!--            fenleiList-->
            <el-cascader
              v-model="selectfenleiList"
              :options="fenleiList"
              :props="fenleiListProps"
              :show-all-levels="false"
              @change="cascader1Change"
              clearable
            ></el-cascader>
            <!--            <el-select v-model="formLabelAlign.grade" placeholder="所属分类">-->
            <!--              <el-option label="0" value="0"></el-option>-->
            <!--            </el-select>-->
          </el-form-item>
        </div>

        <div class="oneLine">
          <el-form-item label="分类名称" prop="name">
            <el-input
              v-model="formLabelAlign.name"
              style="width: 100px"
            ></el-input>
          </el-form-item>
        </div>
        <div class="oneLine">
          <el-form-item label="图片" prop="atavar">
            <div class="unlodBox">
              <el-upload
                class="upload-demo"
                action
                :http-request="uploadFile"
                ref="upload"
                :limit="fileLimit"
                :on-remove="handleRemove"
                :file-list="fileList"
                :on-exceed="handleExceed"
                :before-upload="beforeUpload"
                :show-file-list="false"
                :headers="headers"
              >
                <el-button size="mini" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过5M
                </div>
              </el-upload>
              <el-image
                style="width: 100px; height: 100px"
                :src="formLabelAlign.atavar"
                fit="cover"
              ></el-image>
            </div>
          </el-form-item>
        </div>
        <el-form-item label="">
          <span style="margin-left: 80px">图标尺寸建议：60px*60px</span>
        </el-form-item>
        <div class="oneLine">
          <el-form-item label="排序" prop="sort">
            <el-input
              v-model="formLabelAlign.sort"
              type="number"
              style="width: 100px"
            ></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeVisible('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  uploadFilec,
  goodsSonSort,
  addSort,
  goodSort,
  deleteSort,
  setSort,
} from "../../../../utils/api";
export default {
  name: "materialsSort",
  data() {
    //这里存放数据
    return {
      token: sessionStorage.getItem("token"),
      topInputList: [{ title: "根分类", id: 0 }],
      tableData: [],
      imgHeader: this.Global.imgHeader,

      currentPage: 1,
      total: 0,
      limit: 10,
      loading: true,
      outerVisible: false,
      formLabelAlign: {
        name: "",
        sort: "",
        atavar: "",
        avatar: "",
        id: "",
        parent_id: "",
        status: "",
      },
      fileList: [],
      fileType: ["png", "jpg", "jpeg"],
      fileLimit: 1,
      headers: { "Content-Type": "multipart/form-data" },
      fenleiList: [],
      selectfenleiList: [],
      fenleiListProps: {
        label: "name",
        value: "id",
        children: "child",
        checkStrictly: true,
      },
      leixingList: [],
      bianjiFlag: false,
      dialogTitle: "",
      rules: {
        parent_id: [
          { required: true, message: "请选择品牌分类", trigger: "change" },
        ],
        atavar: [{ required: true, message: "请上传图片", trigger: "change" }],
        name: [{ required: true, message: "请输入名称", trigger: "change" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "change" }],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    cascader1Change(e) {},
    // 是否显示
    switchChange(row) {
      let img = "";
      img = row.image ? row.image : "";
      setSort(
        this.token,
        row.parent_id,
        row.id,
        row.name,
        row.sort,
        img,
        row.status,
        3
      ).then((res) => {
        if (res.data.status) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.goodsSonSort(
            this.token,
            this.currentPage,
            this.limit,
            this.topInputList[this.topInputList.length - 1].id
          );
        }
      });
    },
    // 进入子目录
    subdirectory(index, row) {
      this.topInputList.push({
        title: row.name,
        id: row.id,
      });
      this.goodsSonSort(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[this.topInputList.length - 1].id
      );
    },
    backStor(index, id) {
      console.log();
      if (
        this.topInputList[this.topInputList.length - 1].id ==
        this.topInputList[index].id
      ) {
        return;
      } else {
        this.topInputList.splice(index + 1);
        this.goodsSonSort(
          this.token,
          this.currentPage,
          this.limit,
          this.topInputList[this.topInputList.length - 1].id
        );
      }
    },
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let img = "";
          img = this.formLabelAlign.avatar ? this.formLabelAlign.avatar : "";
          if (this.bianjiFlag) {
            // 编辑
            setSort(
              this.token,
              this.selectfenleiList[this.selectfenleiList.length - 1],
              this.formLabelAlign.id,
              this.formLabelAlign.name,
              this.formLabelAlign.sort,
              img,
              this.formLabelAlign.status,
              3
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                this.outerVisible = false;
                this.$refs.ruleForm.resetFields();
                this.goodsSonSort(
                  this.token,
                  this.currentPage,
                  this.limit,
                  this.topInputList[this.topInputList.length - 1].id
                );
                this.formLabelAlign.name = "";
                this.formLabelAlign.sort = "";
                this.formLabelAlign.atavar = "";
                this.formLabelAlign.avatar = "";
                this.formLabelAlign.id = "";
                this.formLabelAlign.parent_id = "";
                this.formLabelAlign.status = "";
              } else {
                this.$message.error(res.data.msg);
              }
            });
          } else {
            // 创建
            addSort(
              this.token,
              this.selectfenleiList[this.selectfenleiList.length - 1],
              this.formLabelAlign.name,
              this.formLabelAlign.sort,
              img,
              1,
              3
            ).then((res) => {
              if (res.data.status) {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                this.outerVisible = false;
                this.$refs.ruleForm.resetFields();
                this.goodsSonSort(
                  this.token,
                  this.currentPage,
                  this.limit,
                  this.topInputList[this.topInputList.length - 1].id
                );
                this.formLabelAlign.name = "";
                this.formLabelAlign.sort = "";
                this.formLabelAlign.atavar = "";
                this.formLabelAlign.avatar = "";
                this.formLabelAlign.id = "";
                this.formLabelAlign.parent_id = "";
                this.formLabelAlign.status = "";
              } else {
                this.$message.error(res.data.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    closeVisible(formName) {
      this.$refs[formName].resetFields();
      this.outerVisible = false;
      this.formLabelAlign.name = "";
      this.formLabelAlign.sort = "";
      this.formLabelAlign.atavar = "";
      this.formLabelAlign.avatar = "";
      this.formLabelAlign.id = "";
      this.formLabelAlign.parent_id = "";
      this.formLabelAlign.status = "";
    },
    handleClosediaLoding() {
      this.$refs.ruleForm.resetFields();
      this.outerVisible = false;
      this.selectfenleiList = [];
      this.formLabelAlign.name = "";
      this.formLabelAlign.sort = "";
      this.formLabelAlign.atavar = "";
      this.formLabelAlign.avatar = "";
      this.formLabelAlign.id = "";
      this.formLabelAlign.parent_id = "";
      this.formLabelAlign.status = "";
    },
    handleSizeChange(val) {
      this.limit = val;
      // console.log(`每页 ${val} 条`);
      this.goodsSonSort(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[this.topInputList.length - 1].id
      );
    },
    // 第几页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.goodsSonSort(
        this.token,
        this.currentPage,
        this.limit,
        this.topInputList[this.topInputList.length - 1].id
      );
    },
    // 获取列表
    goodsSonSort(token, page, limit, id) {
      this.loading = true;
      goodsSonSort(token, page, limit, id, 3).then((res) => {
        if (res.data.status) {
          this.tableData = res.data.data;
          this.total = res.data.count;
          //status 1显示  2不显示   type
          this.tableData.forEach((item) => {
            item.aimages = [];
            if (item.image) {
              item.aimages.push(this.imgHeader + item.image);
            }
          });
          let timer = setTimeout(() => {
            this.loading = false;
            clearTimeout(timer);
          }, 400);
        } else {
          if (res.data.msg == "token失效,请重新进行登录") {
            this.$router.push("/login");
          }
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      });
    },
    handleEdit(index, row) {
      this.outerVisible = true;
      this.selectfenleiList = [0];
      this.bianjiFlag = false;
      this.dialogTitle = "创建分类";
      this.formLabelAlign.parent_id = 0;
      if (row) {
        this.bianjiFlag = true;
        this.dialogTitle = "编辑分类";
        this.selectfenleiList = [];
        if (row.parent_id == 0) {
          this.selectfenleiList.push(0);
        } else {
          this.selectfenleiList = [row.parent_id];
        }
        this.formLabelAlign.name = row.name;
        this.formLabelAlign.sort = row.sort;
        this.formLabelAlign.atavar = row.aimages[0];
        this.formLabelAlign.id = row.id;
        this.formLabelAlign.avatar = row.image;
        this.formLabelAlign.parent_id = row.parent_id;
        this.formLabelAlign.status = row.status;
      }
    },
    deleteBtn(index, row) {
      this.$confirm("确定删除分类吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteSort(this.token, row.id)
            .then((res) => {
              if (res.data.status) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.goodsSonSort(
                  this.token,
                  this.currentPage,
                  this.limit,
                  this.topInputList[this.topInputList.length - 1].id
                );
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    beforeUpload(file) {
      if (file.type != "" || file.type != null || file.type != undefined) {
        //截取文件的后缀，判断文件类型
        const FileExt = file.name.replace(/.+\./, "").toLowerCase();
        //计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 1; //这里做文件大小限制
        //如果大于50M
        if (!isLt5M) {
          this.$message.error("上传文件大小不能超过 1MB!");
          return false;
        }
        //如果文件类型不在允许上传的范围内
        if (this.fileType.includes(FileExt)) {
          return true;
        } else {
          this.$message.error("上传文件格式不正确!");
          return false;
        }
      }
    },
    handleRemove() {},
    //这是我自定义的移除事件
    handleClose(i) {
      this.fileList.splice(i, 1); //删除上传的文件
    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //上传文件的事件
    uploadFile(item) {
      this.$message("文件上传中........");
      //上传文件的需要formdata类型;所以要转
      uploadFilec(item.file).then((res) => {
        if (res.data.status != false || res.data.id != null) {
          res.data.data.saveurl; //半截
          res.data.data.weburl; //全拼
          this.formLabelAlign.atavar = res.data.data.weburl;
          this.formLabelAlign.avatar = res.data.data.saveurl;
          this.fileList.push(item.file); //成功过后手动将文件添加到展示列表里
          let i = this.fileList.indexOf(item.file);
          this.handleSuccess();
        }
      });
    },
    //上传成功后的回调
    handleSuccess() {
      this.$message({
        message: "上传成功",
        type: "success",
      });
      this.handleClose();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    goodSort(sessionStorage.getItem("token"), 3, "")
      .then((res) => {
        if (res.data.status) {
          this.fenleiList = res.data.data;
          this.fenleiList.unshift({
            id: 0,
            name: "顶级分类",
          });
        } else {
          this.$message.error(res.data.msg);
        }
      })
      .catch((err) => {
        this.$message.error(res.message);
      });
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.toAdd();
    this.goodsSonSort(
      this.token,
      this.currentPage,
      this.limit,
      this.topInputList[this.topInputList.length - 1].id
    );
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped >
#app {
  width: 100%;
}
/deep/.header {
  background: white !important;
  box-shadow: 0 5px 10px #ddd;
  min-height: 40px;
  display: flex;
  padding: 10px;
}
.top-input {
  width: 150px;
  margin-right: 20px;
}
/deep/.el-table th.el-table__cell > .cell {
  text-align: center;
}
/deep/.el-table--border .el-table__cell:first-child .cell {
  text-align: center;
}
/deep/.el-table .cell.el-tooltip {
  text-align: center;
}
.el-table {
  margin: 20px 0;
}
/deep/.el-checkbox:last-of-type {
  margin-left: 0;
}

.oneLine {
  display: flex;
  justify-content: space-between;
}
/deep/.el-dialog__wrapper .el-dialog {
  width: 35%;
}
/deep/.upload-demo .el-upload--text {
  border: none;
  width: auto;
  height: auto;
}
.upload-demo {
  line-height: normal;
  margin-bottom: 20px;
}
.breadItem:hover {
  cursor: pointer;
}
.nametitle:hover {
  cursor: pointer;
  color: #82848a;
}
.beeadBox {
  margin: 20px 0;
}
.nametitle {
  color: #409eff;
}
</style>
